{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### This notebook contains real time implementation code of gunshot detection using SVM linear kernel model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### import libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pyaudio\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib import style\n",
    "import wave\n",
    "import os\n",
    "import librosa\n",
    "import numpy as np\n",
    "import pickle\n",
    "import matplotlib\n",
    "import multiprocessing as mp"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Gun shot detection function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "#audio recording and gunshot detection\n",
    "def detect():\n",
    "    #path where you stored trained model\n",
    "    path=\"E:\\\\All Data\\\\study\\\\MS\\\\2\\\\machine learning\\\\Project\"\n",
    "    feature_length=880 #feature vector length\n",
    "    CHUNK = 1024 #size of each data frame in which audio will be recorded\n",
    "    FORMAT = pyaudio.paInt16\n",
    "    CHANNELS = 1 #recording channel\n",
    "    RATE = 22050 #sampling rate\n",
    "    RECORD_SECONDS =1\n",
    "    name=\"save_training_2.pickle\"\n",
    "    load_training = open(\"E:\\\\All Data\\study\\\\MS\\\\2\\\\machine learning\\\\Project\\\\\"+name,'rb')\n",
    "    clf = pickle.load(load_training) # LOAD TRAINED CLASSIFIER\n",
    "    load_training.close()\n",
    "    while(True):\n",
    "        WAVE_OUTPUT_FILENAME = \"background\"+\".wav\"\n",
    "        p = pyaudio.PyAudio()\n",
    "        #opening stream for recording audio with given parameters\n",
    "        stream = p.open(format=FORMAT,\n",
    "                        channels=CHANNELS,\n",
    "                        rate=RATE,\n",
    "                        input=True,\n",
    "                        frames_per_buffer=CHUNK)\n",
    "        frames = []\n",
    "        #here audio is recorded for time according to given parameters and data is stored in frames\n",
    "        for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n",
    "            data = stream.read(CHUNK)\n",
    "            frames.append(data)\n",
    "        stream.stop_stream() #stop the recording data stream\n",
    "        stream.close() #close the stream\n",
    "        p.terminate()\n",
    "        #now open a wave file with a specified name to store the audio\n",
    "        wf = wave.open(path+\"\\\\\"+WAVE_OUTPUT_FILENAME, 'wb')\n",
    "        wf.setnchannels(CHANNELS)\n",
    "        wf.setsampwidth(p.get_sample_size(FORMAT))\n",
    "        wf.setframerate(RATE)\n",
    "        wf.writeframes(b''.join(frames))\n",
    "        wf.close() #storing of audio is done till here\n",
    "        \n",
    "        #load audio using librosa package \n",
    "        y, sr = librosa.load(path+\"\\\\\"+WAVE_OUTPUT_FILENAME,duration=1)\n",
    "        # extracting MFCC feature of audio\n",
    "        S= librosa.feature.mfcc(y=y, sr=sr, hop_length=512, n_mfcc=20)\n",
    "        S=np.reshape(S,np.product(S.shape))\n",
    "        #making shape equal to 880 equal to feature vector length\n",
    "        if S.shape[0]<feature_length:    \n",
    "            S=np.concatenate((S[0:S.shape[0]],S[S.shape[0]-(feature_length-S.shape[0]):S.shape[0]]))\n",
    "        else:\n",
    "            S=S[0:feature_length]\n",
    "        if clf.predict([S])==1:\n",
    "            print \"Nogunshot\"\n",
    "        else:\n",
    "            print \"Gunshot\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### calling gunshot detection function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n",
      "Nogunshot\n"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-33-61daafb55baa>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0m__name__\u001b[0m\u001b[1;33m==\u001b[0m\u001b[1;34m'__main__'\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m     \u001b[0mdetect\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32m<ipython-input-26-5d234af2b2cb>\u001b[0m in \u001b[0;36mdetect\u001b[1;34m()\u001b[0m\n\u001b[0;32m     26\u001b[0m         \u001b[1;31m#here audio is recorded for time according to given parameters and data is stored in frames\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     27\u001b[0m         \u001b[1;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mRATE\u001b[0m \u001b[1;33m/\u001b[0m \u001b[0mCHUNK\u001b[0m \u001b[1;33m*\u001b[0m \u001b[0mRECORD_SECONDS\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 28\u001b[1;33m             \u001b[0mdata\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mstream\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mCHUNK\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     29\u001b[0m             \u001b[0mframes\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     30\u001b[0m         \u001b[0mstream\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mstop_stream\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m#stop the recording data stream\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mE:\\Anaconda\\lib\\site-packages\\pyaudio.pyc\u001b[0m in \u001b[0;36mread\u001b[1;34m(self, num_frames, exception_on_overflow)\u001b[0m\n\u001b[0;32m    606\u001b[0m                           paCanNotReadFromAnOutputOnlyStream)\n\u001b[0;32m    607\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 608\u001b[1;33m         \u001b[1;32mreturn\u001b[0m \u001b[0mpa\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread_stream\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_stream\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mnum_frames\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mexception_on_overflow\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    609\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    610\u001b[0m     \u001b[1;32mdef\u001b[0m \u001b[0mget_read_available\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "if __name__=='__main__':\n",
    "    detect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
